package cn.sxw.ld.module.member.service.impl;


import cn.sxw.ld.module.pet.service.PetService;
import cn.sxw.ld.module.member.mapper.MemberMapper;
import cn.sxw.ld.module.member.pojo.DailyDataDto;
import cn.sxw.ld.module.member.pojo.Member;
import cn.sxw.ld.module.member.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: SXW
 * @since: 2025年02月20日 11:22
 * @desc:
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private PetService petService;

    @Override
    public Page getPage(int page, int pageSize, String name, int status) {
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        switch (status) {
            case 1: // 1 为空
                break;
            case 2:// 2 为手机
                wrapper.like(Member::getPhone, name);
                break;
            case 3://3 为用户名
                wrapper.like(Member::getMemberName, name);
                break;
        }
        wrapper.ne(Member::getPhone, "18168055774");
        wrapper.eq(Member::getIsDeleted, 0);
        // 按照最后操作时间排序
        wrapper.orderByDesc(Member::getUpdateTime);
        Page pageInfo = new Page(page, pageSize);
        this.page(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public boolean checkSave(Member member) {
        Member one = this.getById(member);
        if (one != null) {
            // 不为空即已存在
            return false;
        } else {
            // 创建时初始化余额和累计充值金额
            member.setBalance(BigDecimal.ZERO);
            member.setTotalRecharge(BigDecimal.ZERO);
            this.save(member);
            return true;
        }
    }

    @Override
    public int getTotalMembers(Date begin, Date end) {
        return baseMapper.getTotalMembers(begin, end);
    }

    @Override
    public List<DailyDataDto> getDailyData(Date begin, Date end) {
        return baseMapper.getDailyData(end, begin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteMemberAndPet(List<String> ids) {
        LambdaUpdateWrapper<Member> memberWrapper = new LambdaUpdateWrapper<>();
        memberWrapper.in(Member::getPhone, ids).set(Member::getIsDeleted, 1);
        boolean dm = this.update(memberWrapper);
        boolean dp = petService.batchDeletePetsByMemberIds(ids);
        return dm && dp;
    }
}
